package cn.itcode_03;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Aaron
 * @since 2021/3/24 9:53
 * <p>描述：</p>
 */
public class Sequence {
    private static final int MAX_NUM = 10;

    private static AtomicInteger ai = new AtomicInteger(0);

    public static int getSequence() {
        while (true) {
            int i = ai.get();
            if (i >= MAX_NUM) {
                if (!ai.compareAndSet(MAX_NUM, 0)) {
                    continue;
                }
            }

            if (ai.compareAndSet(i, ++i)) {
                return i;
            }
        }
    }

    public static void main(String[] args) {
        List<Thread> ts = new ArrayList<>(600);

        for (int i = 0; i < 1000; i++) {
            Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()
                            + " - "
                            + String.format("%02d", getSequence())));
            ts.add(t);
        }

        for (Thread t : ts) {
            t.start();
        }

        for (Thread t : ts) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
